#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fileencoding=utf-8
# vim:tabstop=4
#
# Copyright (c) 2010 by xkhhdx
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import sys
default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
    reload(sys)
    sys.setdefaultencoding(default_encoding)

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.api import memcache
from google.appengine.ext.webapp import template

import base64, logging

import cgi
import wsgiref.handlers

cron_enable = False

if "google.appengine.api" in sys.modules.keys():
    ENV_GAE = "GAE"
else:
    ENV_GAE = "Local"

class UserManages(db.Model):
    user = db.UserProperty()
    serviceprovider = db.StringProperty()
    config = db.StringProperty()
    create_time = db.DateTimeProperty(auto_now_add=True)

def query_usermanage():
    msg=db.GqlQuery("SELECT * FROM UserManages ORDER BY create_time")

    if msg.count():
        return msg
    else:
        #lastestitem = UserManages()
        #lastestitem.serviceprovider = "follow5"
        #lastestitem.config = "{'username' : '','password' : '',}"
        #lastestitem.put()

        return [] #[lastestitem]:

def load_usermanage(force_query = False):
    data = memcache.get("UserManages")
    if data is not None and not force_query:
#        logging.info("using memcache -- UserManages")
#        logging.info("    `data` = " + `data`)

        return data
    else:
  #      logging.info("querying db -- UserManages")
        
        data = query_usermanage()
        memcache.add("UserManages", data, 3630)
        return data


def refresh_usermanage_cache(lastestitem = None):
    memcache.delete("UserManages")
    load_usermanage( True )

    return lastestitem


class Settings(db.Model):
    config = db.StringProperty()
    update_time = db.DateTimeProperty(auto_now_add=True)


aa="""
    def __getitem__(self, key):
        cfg = eval(self.config)
        return cfg[key]

    def __setitem__(self, key, val):
        cfg = eval(self.config)
        cfg[key] = val
        config = `cfg`
"""
configs = {
    }

def query_setting():
    msgs=db.GqlQuery("SELECT * FROM Settings ORDER BY update_time")
    if msgs.count():
        return msgs[0], True
    else:
        return save_setting (Settings()), False

def load_setting(force_query = False):
    data = memcache.get("configs")
    if data is not None and not force_query:
   #     logging.info("using memcache")
   #     logging.info("    `data` = " + `data`)

        return data, True
    else:
    #    logging.info("querying db")
        
        data, ret = query_setting()
        memcache.add("configs", data, 3630)
        return data, ret

def save_setting(lastestitem = None):

    msgs=db.GqlQuery("SELECT * FROM Settings ORDER BY update_time")
    if not msgs.count():
        msgs = [Settings()]
    if not lastestitem:
        lastestitem = msgs[0]

    lastestitem.config = `configs`
    lastestitem.put()

    if memcache.get("configs") is not None:
        memcache.set("configs", lastestitem, 3630)
    else:
        memcache.add("configs", lastestitem, 3630)

    return lastestitem

configs, cron_enable = load_setting()
configs = eval(configs.config)

import bitly
bitlyapi = None
if cron_enable:
    try:
        import fetcher, updaters
        fetcher.__api__ = configs ["stapi"]
        updaters.follow5.__api__ = configs ["f5api"]
        #print "login="+configs["bitlyusername"]+", apikey="+configs["bitlyapikey"]
		bitlyapi = bitly.Api(login=configs["bitlyusername"], apikey=configs["bitlyapikey"])

    except Exception, e:
        #logging.info("configure mod __main__ block if cron_enable block exception: " + e)
        pass
        

def reload_all():
	print "UserManages<br/>"
    memcache.delete("UserManages")
    load_usermanage( True )
    
	print "configs<br/>"
    memcache.delete("configs")
	configs, cron_enable = load_setting(True)
	
	print "lastestitem<br/>"
    memcache.delete("lastestitem")


